package com.suanfa.island;

/**
 * 计算二维数组中岛屿的数量
 */
public class IsLandCount2 {

    public static void main(String[] args) {
        int[][] arr =
                {
                        {1,1,1,1,0},
                        {1,1,0,1,0},
                        {1,1,0,0,0},
                        {0,0,0,0,0}
                };
        int[][] arr2 ={
                {1,1,0,0,0},
                {1,1,0,0,0},
                {0,0,1,0,0},
                {0,0,0,1,1}
        };
        System.out.println(numIslands(arr2));
    }


    public static int numIslands(int[][] arr){
            int count = 0;
            for(int r = 0; r< arr.length; r++){
                for(int c = 0; c < arr.length; c++){
                    if(arr[r][c] == 1){
                        readArrs(arr, r, c);
                        count++;
                    }
                }
            }
            return count;
        }

        static void readArrs(int[][] arr, int r, int c){
            if(!inArea(arr,r, c)){
                return;
            }
            if(arr[r][c] != 1){//海洋或者已经遍历过
                return;
            }
            arr[r][c] = 2;
            //拓展到相邻陆地
            readArrs(arr, r+1, c);
            readArrs(arr, r-1, c);
            readArrs(arr, r, c+1);
            readArrs(arr, r, c-1);

        }
        public static boolean inArea(int[][] arr, int r, int c){
            return c>=0 && r>=0 && r< arr.length && c< arr[0].length;
        }
}
